#!/bin/bash
# ============================================================
# Harbor 2.8.2 一键部署脚本（WSL Ubuntu + Docker Desktop 集成）
# ============================================================

set -e

# ----------------------------
# 配置参数
# ----------------------------
HARBOR_VERSION="v2.8.2"
HARBOR_DIR="/root/harbor"  # 设置目标目录为 /root/harbor
HARBOR_TGZ="harbor-online-installer-${HARBOR_VERSION}.tgz"
HARBOR_URL="https://github.com/goharbor/harbor/releases/download/${HARBOR_VERSION}/${HARBOR_TGZ}"
HARBOR_HOSTNAME=$(hostname -I | awk '{print $1}')   # 使用 WSL 本机局域网 IP
HARBOR_ADMIN_PASS="Harbor12345"
HARBOR_HTTP_PORT="5000"

# ----------------------------
# 下载 Harbor 安装包
# ----------------------------
mkdir -p "$HARBOR_DIR"
cd "$HARBOR_DIR"

# 如果没有下载过 Harbor 安装包，则下载
if [ ! -f "$HARBOR_TGZ" ]; then
    echo "Downloading Harbor ${HARBOR_VERSION}..."
    wget "$HARBOR_URL"
fi

# ----------------------------
# 解压 Harbor 安装包
# ----------------------------
echo "Extracting Harbor package..."
tar xf "$HARBOR_TGZ" --strip-components=1  # 使用 --strip-components=1 来避免解压到 /root/harbor/harbor
cd "$HARBOR_DIR"

# ----------------------------
# 设置权限
# ----------------------------
chmod +x prepare install.sh
sudo chown -R $USER:$USER "$HARBOR_DIR"

# ----------------------------
# 生成 harbor.yml
# ----------------------------
cp harbor.yml.tmpl harbor.yml

sed -i "s|^hostname:.*|hostname: ${HARBOR_HOSTNAME}|g" harbor.yml
sed -i "s|^harbor_admin_password:.*|harbor_admin_password: ${HARBOR_ADMIN_PASS}|g" harbor.yml
sed -i "s|^  port:.*|  port: ${HARBOR_HTTP_PORT}|g" harbor.yml
# 注释 https 配置，使用 http
sed -i '/https:/,/^[^ ]/ s/^/#/' harbor.yml

# ----------------------------
# 执行 prepare
# ----------------------------
echo "Running prepare..."
sudo ./prepare

# ----------------------------
# 执行 install 并启动 Harbor
# ----------------------------
echo "Installing and starting Harbor..."
sudo ./install.sh
docker compose up -d

# ----------------------------
# 输出访问 URL
# ----------------------------
echo "========================================"
echo "Harbor 已启动成功！"
echo "访问地址: http://${HARBOR_HOSTNAME}:${HARBOR_HTTP_PORT}"
echo "管理员账号: admin"
echo "管理员密码: ${HARBOR_ADMIN_PASS}"
echo "========================================"
